import { defineStore } from 'pinia';
import { store } from '../index';
import type {RouteRecordRaw} from "vue-router";
import constantRoutes ,{accessRoutes,publicRoutes} from "../../router/router.config";

import fetchApi from '../../api/user/index'

interface PerMissIoState {
    isGetUserInfo: boolean; // 是否获取过用户信息
    isAdmin: 0 | 1; // 是否为管理员
    auths: string[]; // 当前用户权限
    modules: string[]; // 模块权限
}

export const usePerMissIoStore = defineStore({
    id:'app-permission',
    state:():PerMissIoState=>({
        isGetUserInfo: false, // 未对接口开发阶段暂定true
        isAdmin: 0,
        auths: [],
        modules: [],
    }),
    getters: {
        getAuths(): string[] {
            return this.auths;
        },
        getModules(): string[] {
            return this.modules;
        },
        getIsAdmin(): 0 | 1 {
            return this.isAdmin;
        },
        getIsGetUserInfo(): boolean {
            return this.isGetUserInfo;
        },
    },
    actions: {
        // 储存当前权限
        setAuth(auths:string[],modules:string[]){
            this.auths = auths
            this.isGetUserInfo = true
            this.modules = modules
        },
        // 判断当前用户是否是管理员
        setIsAdmin(isAdmin: 0 | 1) {
            this.isAdmin = isAdmin;
        },
        // 重置当前所有数据
        resetState() {
            this.isGetUserInfo = false;
            this.isAdmin = 0;
            this.auths = [];
            this.modules = [];
        },
        // 获取当前用户信息及权限 此方法必须储存 用户角色 及权限 不然会造成路由死循环
        async fetchAuths() {
            const {auths,isAdmin,modules} = await fetchApi.permission()

            this.setAuth(auths,modules);
            this.setIsAdmin(isAdmin || 0)

        },
        // 获取后台返回路由信息
        async buildRoutesAction():Promise<RouteRecordRaw[]>{
            let routes: RouteRecordRaw[] = [...constantRoutes,...accessRoutes,...publicRoutes]

            if(this.isAdmin != 1){
                // 过滤权限信息
                // return routes
            }
            return routes
        }
    }
})

export const usePerMissIoStoreWithOut = ()=>{
    return usePerMissIoStore(store)
}

